<template>
  <div class="satisfied">
    <div class = "wrap-save">
      <el-button class = "primary_btn" @click = "addTag"><span>{{$t('public.add')}}</span></el-button>
      <el-button class = "primary_btn" :loading = "refreshLoading" @click = "refresh"><span>{{$t('public.refresh')}}</span></el-button>
      <el-button type = "primary" @click = "save" class = "save primary_btn">{{$t('public.save')}}</el-button>
    </div>
    <div class="drag thead">
      <div class="item">{{$t('configLazyLoad.channel.option')}}</div>
      <div class="tag">{{$t('configLazyLoad.channel.tagLine')}}</div>
      <div class="item opt">{{$t('public.operate')}}</div>
    </div>
    <!-- 无评价的提示 -->
    <div class="footer" v-show = "CSRDic.length === 0">{{$t('configLazyLoad.channel.mailTip39')}}</div>
    <!-- draggable可拖拽的包裹 github地址  https://github.com/SortableJS/Vue.Draggable
         :list 绑定可拖拽的数组
         :options 为拖拽的配置，当前组件只是设置了指定的拖拽元素,详情 https://github.com/RubaXa/Sortable#options
     -->
    <draggable class="list-group"
               :options="dragOptions"
               :list="CSRDic"
               v-show = "CSRDic.length !== 0">
      <div v-for="(item, index) in CSRDic" class="drag">
        <div class="item sdsd">
          <!-- 设置拖动的元素 透明度为0 占位 -->
          <div class="move">{{$t('configLazyLoad.channel.mailTip40')}}</div>
          <el-input v-model="item.name"
                    size="mini"
                    @blur = "isNull(index)"
                    :maxlength="8"
                    :placeholder = "item.nameTip ? item.nameTip : ''"></el-input></div>
        <div class="tag">
          <el-input v-for="(i, index) in 6"
                    size="mini"
                    :maxlength="6"
                    v-model="item.reason[i-1]"
                    :placeholder = "item.conten ? item.conten[i -1] : ''"
                    :class = "[index < 3 ? 'ipt' : '']"></el-input></div>
        <div class="item del">
                <span @click="del(index)"
                      class="btn_del">{{$t('public.delete')}}</span></div>
      </div>
    </draggable>
    <affix :label="$t('configLazyLoad.channel.mailTip42')"></affix>
    <div class="satisfied_edit_box">
      <div class="wrap-save clearfix">
        <el-button class="primary_btn" @click="edit(true)">{{$t('public.edit2')}}</el-button>
        <el-button class="primary_btn" @click="edit()">{{$t('configLazyLoad.channel.mailTip41')}}</el-button>
        <el-button type = "primary"
                   @click = "saveSatisfied"
                   class = "save primary_btn">{{$t('public.save')}}</el-button>
      </div>
      <el-form v-show="!editConShow" :rules="rules" class="mail_satisfied_editor" :model="editConShowHtml" ref="editConShowHtml" label-position="top" label-width="80px">
        <el-form-item :label="$t('configLazyLoad.channel.mailTip43')" prop="title">
          <el-input v-model.trim="editConShowHtml.title"></el-input>
        </el-form-item>
        <el-form-item :label="$t('configLazyLoad.channel.mailTip45')">
          <div class="tip_item">{{$t('configLazyLoad.channel.mailTip44')}}</div>
          <div id="mail_satisfied_edit"></div>
        </el-form-item>
      </el-form>
      <div v-show="editConShow" class="edit_box_show">
        <div>{{$t('configLazyLoad.channel.mailTip43')}} {{editConShowHtml.title}}</div>
        <div>{{$t('configLazyLoad.channel.mailTip45')}}</div>
        <div  v-html="editConShowHtml.content"></div>
      </div>
    </div>
  </div>
</template>
<script>
  import draggable from 'vuedraggable'
  import affix from '@/components/ui-modules/affix/Affix.vue'
  import {deepClone, filterXSS} from '@utils/m7Utils'
  import { uploadTo7moorEmailDomain } from '@utils/qiniuUtils'
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  export default {
    name: 'MailSatisfied',
    data () {
      return {
        CSRDic: [],
        refreshLoading: false,
        _id: '',
        editConShow: false,
        editConShowHtml: {
          title: '',
          content: ''
        },
        editor: {},
        rules: {
          title: [
            { required: true, message: this.$t('configLazyLoad.channel.mailTip46'), trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      // 选项名称失去焦点触发的事件
      isNull (index) {
        if (!this.CSRDic[index].name) {
          this.$message.error(this.$t('configLazyLoad.channel.mailTip47', {num: index + 1}))
        }
      },
      // 添加一个满意度
      addTag () {
        if (this.CSRDic.length === 5) {
          this.$message(this.$t('configLazyLoad.channel.mailTip48'))
          return
        }
        // 保证每个input都能绑定一个
        // reason, conten 保存时不需要传的数据, 目的只是为了渲染满意度配置项,保存时有处理
        let tag = {
          name: '',
          index: this.CSRDic.length,
          nameTip: this.$t('configLazyLoad.channel.mailTip49'),
          key: uuid.v1(),
          reason: ['', '', '', '', '', ''],
          conten: [this.$t('configLazyLoad.channel.mailTip50'), this.$t('configLazyLoad.channel.mailTip51'), this.$t('configLazyLoad.channel.mailTip52'), this.$t('configLazyLoad.channel.mailTip53'), this.$t('configLazyLoad.channel.mailTip54'), this.$t('configLazyLoad.channel.mailTip55')]
        }
        this.CSRDic.push(tag)
      },
      edit (flag) {
        if (flag) {
          this.editConShow = false
        } else {
          this.editConShow = true
          this.editConShowHtml.content = this.editor.txt.html()
        }
      },
      refresh () {
        this.refreshLoading = true
        window.setTimeout(() => {
          this.refreshLoading = false
        }, 400)
        this.getView()
      },
      // 删除一个满意度
      del (index) {
        this.CSRDic.splice(index, 1)
      },
      // 获取满意度配置数据
      getView () {
        let data = {
          type: 'emailCSR'
        }
        this.$store.dispatch('getCSRDic', data).then(res => {
          if (res && res.success && res.row) {
            this._id = res.row._id
            this.CSRDic = this.inti(res.row.options)
            if (res.row.subject) {
              this.editConShowHtml.title = res.row.subject
            }
            if (res.row.content || typeof res.row.content === 'string') {
              this.editor.txt.html(filterXSS(res.row.content))
            } else {
              let str = this.$t('configLazyLoad.channel.mailTip56')
              this.editor.txt.html(filterXSS(str))
            }
          } else {
            this.CSRDic = []
            let str = this.$t('configLazyLoad.channel.mailTip56')
            this.editor.txt.html(filterXSS(str))
          }
        })
      },
      // 初始化数据，保证每个input都会绑定一个数据
      inti (obj) {
        if (obj.length === 0) {
          return []
        }
        for (let j = 0; j < obj.length; j++) {
          for (let i = 0; i < 6; i++) {
            if (!obj[j].reason[i]) {
              obj[j].reason[i] = ''
            }
          }
        }
        return obj
      },
//      初始化满意度内容
      initEditor () {
        this.editor = new Editor('#mail_satisfied_edit')
        this.editor.config.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
          'strikeThrough',  // 删除线
          'foreColor',  // 文字颜色
          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
          'justify',  // 对齐方式
          'quote',  // 引用
          // 'emoticon',  // 表情
          'table',  // 表格
          // 'code',  // 插入代码
          'undo',  // 撤销
          'redo'  // 重复
        ]
        this.editor.config.pasteTextHandle = filterXSS
        this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
        this.editor.config.zIndex = 100
        let lang = window.langJson || {}
        let editLang = lang.wangeditor
        this.editor.config.lang = editLang
        this.editor.create()
//        添加图片上传组件
        let div = document.createElement('div')
        div.className = 'w-e-menu'
        div.style.cssText = 'z-index:101;'
        let span = document.createElement('i')
        span.className = 'w-e-icon-image'
        span.id = 'w-e-img-icon'
        div.appendChild(span)
        if (document.getElementsByClassName('w-e-toolbar')[0]) {
          document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
        }
//        初始化图片上传组件
        this.initUploadImageFile()
      },
//        初始化图片上传组件
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        uploadTo7moorEmailDomain(this.sessionUserId, 'w-e-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
      },
      // 保存满意度配置
      save () {
        let isName = true
        // 判断选项名是否为空
        this.CSRDic.map(item => {
          if (!item.name) {
            isName = false
          }
        })
        if (!isName) {
          this.$message.error(this.$t('configLazyLoad.channel.mailTip57'))
          return
        }
        let data = {
          _id: this._id,
          type: 'emailCSR',
          options: deepClone(this.CSRDic)
        }
        for (let j = 0; j < data.options.length; j++) {
          var _reason = []
          for (let i = 0; i < 6; i++) {
            if (data.options[j].reason[i]) {
              _reason.push(data.options[j].reason[i])
            }
          }
          if (data.options[j].nameTip) {
            delete data.options[j].nameTip
          }
          if (data.options[j].conten) {
            delete data.options[j].conten
          }
          data.options[j].reason = _reason
          data.options[j].index = j
        }
        this.$store.dispatch('saveEmailCSRDic', data).then(res => {
          if (res && res.success) {
            this.$message.success(this.$t('config.channel.configSuccess'))
          }
        })
      },
//      保存邮件满意度内容
      saveSatisfied () {
        this.$refs['editConShowHtml'].validate((valid) => {
          if (valid) {
            let str = this.editor.txt.html()
            let num = (str.split('{linkUrl}')).length - 1
            if (num > 1) {
              this.$message.error(this.$t('configLazyLoad.channel.mailTip58'))
              return
            } else if (num < 1) {
              this.$message.error(this.$t('configLazyLoad.channel.mailTip58'))
              return
            }
            let data = {
              _id: this._id,
              subject: this.editConShowHtml.title,
              content: str
            }
            this.$store.dispatch('saveEmailCSRDic', data).then(res => {
              if (res && res.success) {
                this.$message.success(this.$t('config.channel.configSuccess'))
              }
            })
          }
        })
      }
    },
    components: {
      draggable,
      affix
    },
    computed: {
      // 计算拖拽的配置
      dragOptions () {
        return {
          handle: '.move'
        }
      },
      sessionUserId () {
        return this.$store.state.session.user._id
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.initEditor()
      })
    },
    beforeMount () {
      this.getView()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .satisfied
    padding 20px
    overflow-y scroll
    height calc(100vh - 170px)
    box-sizing border-box
    .footer
      height 60px
      text-align center
      line-height 60px
      font-size 16px
    .thead
    .drag:nth-child(even)
    .drag:hover
      background $c-card
    .drag
      padding 10px 20px 10px 16px
      display flex
      align-items center
      position relative
      border-bottom 1px solid $c-tree
      .del
        text-align right
        color $c-pink
        position relative
        .btn_del
          cursor pointer
          position absolute
          right 0
      .item
        width 20%
        .move
          position absolute
          width 100%
          height 100%
          opacity 0
          left 0
          top 0
          cursor move
      .tag
        display flex
        padding 0 20px
        flex-wrap wrap
        width 60%
        .el-input
          flex-basis 30%
          flex-grow 1
          padding 10px 10px 0 0
          flex-shrink 1
        .ipt
          padding-top 0
    .thead
      font-weight bold
      .opt
        text-align right
    .wrap-save
      height 30px
      padding 20px 20px
      text-align right
  .list-group
    border 1px solid #ebebeb
  .ui-affix
    margin-top 40px
    padding 0 20px 16px
  .edit_box_show
    width 100%
    overflow-x auto
  .tip_item
    color $cf-gray4
    font-size 12px
    padding 5px 0
    line-height 16px
</style>
